﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Log;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Log
{
    public class DelLogHandler : IRequestHandler<DelLogCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogModel> logRepo;
        private readonly IMapper mapper;
        /// <summary>
        /// 通过构造函数注入日志仓储和automapper
        /// </summary>
        /// <param name="logRepo"></param>
        /// <param name="mapper"></param>
        public DelLogHandler(IBaseRepository<LogModel> logRepo,IMapper mapper)
        {
            this.logRepo = logRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 更新日志的中介者处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(DelLogCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();


            //1.检查前端是否传来id

            //2.通过id查找要更新的实体
            var log = logRepo.GetModel(request.Id); //
            if (log == null) {
                result.Data = 0;
                result.Code = ApiEnums.Error;
                result.Msg = "要删除的日志数据不存在";
            }
            //3.给实体赋值
            log.IsDeleted = true;
            //4.调用仓储的Del方法,保存更改数据
            var r = logRepo.Update(log);

            if(r > 0)
            {
                result.Code = ApiEnums.Success;
                result.Msg = "删除日志成功!";
                result.Data = r;
            }
            else
            {
                result.Code = ApiEnums.Fail;
                result.Msg = "删除日志失败!";
                result.Data = r;
            }

            return Task.FromResult(result);
             
        }
    }
}
